package com.hmall.common.config;

import cn.hutool.core.util.ObjectUtil;
import com.hmall.common.utils.RabbitMqHelper;
import com.hmall.common.utils.UserContext;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Type;

// 添加这个类，是为了在发送消息的时候，添加userId
@Configuration
// 添加这个注解，是为了限制仅在RabbitTemplate类存在的情况下才加载这个配置
@ConditionalOnClass(value = {RabbitTemplate.class, MessageConverter.class})
public class RabbitConfig {
    @Bean
    public MessageConverter messageConverter(){
        Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter(){
            @Override
            public Object fromMessage(Message message) throws MessageConversionException {
                Long userId = message.getMessageProperties().getHeader("user-info");
                if(ObjectUtil.isNotEmpty(userId)){
                    UserContext.setUser(userId);
                }
                return super.fromMessage(message);
            }

            @Override
            protected Message createMessage(Object objectToConvert, MessageProperties messageProperties, Type type) throws MessageConversionException {
                Long userId = UserContext.getUser();
                if(ObjectUtil.isNotEmpty(userId)){
                    messageProperties.setHeader("user-info", userId);
                }
                return super.createMessage(objectToConvert, messageProperties,type);
            }
        };
        converter.setCreateMessageIds(true);
        return converter;
    }

    @Bean
    public RabbitMqHelper rabbitMqHelper(RabbitTemplate rabbitTemplate){
        return new RabbitMqHelper(rabbitTemplate);
    }
}
